#!/bin/bash
if [ $# -lt 1 ];then
  echo "Usage: $0 [picDirPath]"
  exit 1
fi

# Delete cached files
rm -f mp4merge.list
rm -rf mp4Cache/*

mp4Index=0
picDirPath=$1
picList=$(ls -t ${picDirPath})
for ip in ${picList}
do
  echo "${ip} 720p padding..."
  python3 pilPadding.py "${picDirPath}/${ip}" "mp4Cache/${mp4Index}.jpg" 

  echo "${ip} ==> ${mp4Index}.mp4"
  ffmpeg -hide_banner -f image2 -loop 1 -i "mp4Cache/${mp4Index}.jpg" -pix_fmt yuvj420p -vcodec libx264 -r 20 -t 2 -y -f mp4 "mp4Cache/${mp4Index}.mp4" 2>/dev/null 1>/dev/null
  let mp4Index=$((${mp4Index}+1))

  # ffmpeg -hide_banner -f image2 -loop 1 -i "${picDirPath}/${ip}" -vf "scale=iw:ih:force_original_aspect_ratio=decrease,pad=iw:ih:(1280-iw)/2:(720-ih)/2" -pix_fmt yuvj420p -vcodec libx264 -s 1280*720 -r 20 -t 2 -y -f mp4 "mp4Cache/${mp4Index}.mp4" 2>/dev/null 1>/dev/null
  # ffmpeg -hide_banner -f image2 -loop 1 -i "${picDirPath}/${ip}" -vf "scale=iw:ih:force_original_aspect_ratio=decrease,pad=iw:ih:(1280-iw)/2:(720-ih)/2" -f lavfi -i anullsrc=channel_layout=stereo:sample_rate=44100 -acodec aac -ar 32000 -ac 2 -pix_fmt yuvj420p -vcodec libx264 -s 1280*720 -r 20 -t 2 -y -f mp4 "mp4Cache/${mp4Index}.mp4" 2>/dev/null 1>/dev/null
  # ffmpeg -hide_banner -f image2 -loop 1 -i "${picDirPath}/${ip}" -f lavfi -i anullsrc=channel_layout=stereo:sample_rate=44100 -acodec aac -ar 32000 -ac 2 -pix_fmt yuvj420p -vcodec libx264 -s 720*1280 -r 20 -t 2 -y -f mp4 "mp4Cache/${mp4Index}.mp4" 2>/dev/null 1>/dev/null
done

if [ ! -f mp4Cache/0.mp4 ];then
  echo "jpg==>mp4 failure..."
  exit -2
fi

#echo "file logo.mp4" > mp4merge.list
for iv in $(ls mp4Cache/*.mp4)
do
  echo "file $iv"
done >> mp4merge.list
ffmpeg -hide_banner -f concat -safe 0 -i mp4merge.list -c copy -y "${picDirPath}.mp4"
exit 0

